#include "mainwindow.h"
#include <QApplication>
#include <QKeyEvent>
#include <QDebug>
#include <QList>
#include <QDesktopWidget>
#include <QThread>
#include <QPoint>
#include <QTime>
#include "aboutwidget.h"
#include "customstyle.h"
#include <QDesktopWidget>
#include <sys/file.h>
#include "util/unix_signals.h"
#include "util/xatom-helper.h"
#include "util/theme_util.h"
#include <sys/file.h>
#include <fcntl.h>

#define NUMBER_LOAD 1   //加载数量
#define COUNTDOWN_TIME 3 //倒计时时间
#define TABWINDOWWIDETH 80                   //窗口宽度
#define TABWINDOWHEIGHT 84                   //窗口高度
#define TABTITLEHEIGHT 42                    //标题栏高度
#define TABSHADOWWIDTH 6                     //阴影宽度
#define TABWIDGETRADIUS 6                    //窗口圆角
#define TABBUTTONRADIUS 6                    //按钮圆角
#define TABSHADOWALPHA 0.08                  //阴影透明度

#define ABOUTWINDOWWIDETH  420                 //窗口宽度
#define ABOUTWINDOWHEIGHT  316                 //窗口高度
#define ABOUTTITLEHEIGHT 42                    //标题栏高度
#define ABOUTSHADOWWIDTH 6                     //阴影宽度
#define ABOUTWIDGETRADIUS 6                    //窗口圆角
#define ABOUTBUTTONRADIUS 6                    //按钮圆角
#define ABOUTSHADOWALPHA 0.08                  //阴影透明度
#define TRANS_PATH  "/usr/share/translations/"
//相册宽度
#define picture_width 270
int MainWindow::picture_number;
QGSettings *MainWindow::setting;
QString user; // 用户名
bool MainWindow::mirrorFlag; //镜像flag lhl debug
QString video_path; //最后录像
QString video_path_n; //新生成录像
QString photoFormat;
QString videoFormat;

static const QString FM1_DEST = "org.freedesktop.FileManager1";
static const QString FM1_PATH = "/org/freedesktop/FileManager1";
static const QString FM1_IFACE = "org.freedesktop.FileManager1.ShowItems";

MainWindow::MainWindow(QStringList strList,QWidget *parent)
   : QWidget(parent),m_dbusHanler(nullptr)
{
    if(setting->isSchemaInstalled("org.kylin-camera.settings")){
        setting = new QGSettings("org.kylin-camera.settings");
        qDebug() << "success";
    }
    else{
        qDebug() << "fail";
        exit(0);
    }
    //注册Dbus服务
//    QDBusConnection sessionBus = QDBusConnection::sessionBus();
//    if(sessionBus.registerService("org.ukui.kylin_camera"))
//    {
//        sessionBus.registerObject("/org/ukui/kylin_camera","mainwindow.kylin_camera",this,
//                                  QDBusConnection::ExportAllSlots);

//        qDebug()<<"初始化DBUS成功";
//    }
//    else{
//        qDebug()<<"初始化DBUS失败";
//    }

//    user = qgetenv("USER");//获取当前用户名
    //互斥锁，防止打开多个程序
//    int fd = open(TRANS_PATH,O_RDONLY);
//    flock(fd,LOCK_UN);
//    if(fd == -1) exit(0);
//    int ret = flock(fd,LOCK_EX | LOCK_NB);
//    qDebug() << "user1:" << user <<"setting-:" << setting->get("user").toString(); //增加其他用户在摄像头使用时，打开摄像头，提示弹框。问题：在其他用户上无法获取到系统用户名
//    if(ret == -1){
//        if(user != "" && user != setting->get("user").toString() && setting->get("user").toString() != ""){
//            QMessageBox::warning(this,tr("waring"),tr("other user already open device!"));
//            exit(0);
//        }
//        if(user != "" && user != setting->get("user").toString()){
//               QMessageBox::warning(this,tr("waring"),tr("other user already open device!"));
//               exit(0);
//         }
//        qDebug() << "进入dbus";
//        QDBusInterface interface( "org.ukui.kylin_camera", "/org/ukui/kylin_camera","mainwindow.kylin_camera", QDBusConnection::sessionBus());
//        interface.call("kylin_camera_play_request", strList);
//        qDebug () << "按任意键继续..";
//        exit(0);
//    }
//    setting->set("user",user);
    m_currentUser = qgetenv("USER");
    qDebug() << "USER =" << qgetenv("USER");
    if (m_currentUser.isEmpty())
        m_currentUser = qgetenv("USERNAME");
        //应用单例和终端命令处理
    if (singleInstance(strList) == false) {
        exit(0);
    }
    setting->set("user",m_currentUser);
    proc = new QProcess();  //启动一个进程
    //设置标题栏窗口显示
   setWindowTitle(tr("kylin-camera"));
   //setWindowIcon(QIcon::fromTheme("kylin-camera"));
    //从配置文件读取
    imagePath = setting->get("save-path").toString();  //static QGSettings *setting; 从GSettings中获取
    //判断从Qsetting中获取路径
    //imagePath = ""; //test
    //setting->set("save-path","");//test
    if(imagePath.compare("") == 0)
    {
        imagePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
        QString locale = QLocale::system().name();
        if (locale == "zh_CN")
        {
            imagePath += QStringLiteral("/视频/");
        }
        else
        {
            imagePath += "/Videos/";
        }
        QDir dir(imagePath);
        if (!dir.exists()) {
            dir.mkpath(imagePath);
        }
        //路径写入
        setting->set("save-path",imagePath);
        qDebug()<<"path:"<<imagePath;
    }

    //从配置文件读取，默认为3
    dead_time_sec = COUNTDOWN_TIME;
    setCommonUI();

    //将上次的拍照和录像保存
    //对相册中之前的文件进行读取
     QString filename = setting->get("filename").toString();
     if(QFile(filename).exists()){
         imageView(filename,setting->get("is-video").toBool());
     }
    //检测设备发生变化
    watcher = new QFileSystemWatcher;
    watcher->addPath("/dev/");
    devRead = new DeviceRead;
    connect(devRead,&DeviceRead::finish,camerapage,&CameraPage::timeEvent);
    connect(devRead,&DeviceRead::finish,setPage,&SettingPage::change_item);

    //启动计时器，监听设备，
    connect(watcher,&QFileSystemWatcher::directoryChanged,devRead,[=](){devRead->start();});

    //setWindowIcon(QIcon(":/image/camera-app@2x.png"));
    //setWindowIcon(QIcon::fromTheme("kylin-camera")); //适应主题
    //阻止锁屏
//    QDBusConnection::systemBus().connect(QString("org.freedesktop.login1"), QString("/org/freedesktop/login1"),
//                                         QString("org.freedesktop.login1.Manager"), QString("PrepareForShutdown"),
//                                         this, SLOT(onPrepareForShutdown(bool)));
//    QDBusConnection::systemBus().connect(QString("org.freedesktop.login1"), QString("/org/freedesktop/login1"),
//                                         QString("org.freedesktop.login1.Manager"), QString("PrepareForSleep"),
//                                         this, SLOT(onPrepareForSleep(bool)));
//    QDBusConnection::sessionBus().connect(QString("org.ukui.ScreenSaver"),
//                                          QString("/"),QString("org.ukui.ScreenSaver"),
//                                          QString("lock"),this,SLOT(exception_handing()));

//   QDBusConnection::sessionBus().connect(QString("org.ukui.ScreenSaver"),
//                                          QString("/"),QString("org.ukui.ScreenSaver"),
//                                         QString("lock"),this,SLOT(onLocked()));

//    QDBusConnection::sessionBus().connect(QString("org.ukui.ScreenSaver"),
//                                          QString("/"),QString("org.ukui.ScreenSaver"),
//                                          QString("unlock"),this,SLOT(onUnlocked()));
#ifdef __V10__
    this->setStyleSheet("MainWindow{background-color:#000000;}");
#endif
    this->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed); //保存默认布局
//    m_dbus = new dbusManager;
    //connect signals08
    //
//    m_dbusHanler = new DaemonIpcDbus;
//    connect(m_dbusHanler,SIGNAL(request(QStringList)),this,SLOT(kylin_camera_play_request(QStringList)));    
	initDbus();
}

MainWindow::~MainWindow()
{
    qDebug() << "kill them all";
    if(camerapage->server->isValid()){
        camerapage->server->call("Uninhibit",camerapage->arg_0);
    }
    if(camerapage->camera && Button::video_mode){
        camerapage->camera->camera_stop_record();
    }
    if(camerapage->camera) {
        delete camerapage->camera;
    }
    pTitleBar->deleteLater();
    viewpage->deleteLater();
    setWid->deleteLater();
    camerapage->deleteLater();
    setPage->deleteLater();
    m_dbus->deleteLater();
    m_dbusHanler->deleteLater();
    exit(0);
}

//总体页面布局，设置公共组件连接槽函数
void MainWindow ::setCommonUI(){
#ifdef __V10__
    this->setWindowFlags(Qt::FramelessWindowHint);
#endif
    // 窗体透明
//    this->setAttribute(Qt::WA_TranslucentBackground, true);

    // 标题栏
    pTitleBar = new TitleBar(this);
    viewpage = new PictureViewPage(this);
    setWid = new Setting(this);
    camerapage = new CameraPage(this);
    setPage = new SettingPage();
    pTitleBar->funcListButton->setMenu(setWid->menu);
    setWid->hide();
    setPage->current_dir = imagePath;
//    setPage->current_dir_lab->setText(imagePath);
//    setPage->current_dir_lab->setToolTip(imagePath);
    setPage->raise();

    StyleWidgetAttribute aboutWin(ABOUTWINDOWWIDETH,ABOUTWINDOWHEIGHT,0,ABOUTWIDGETRADIUS,ABOUTSHADOWWIDTH,ABOUTSHADOWALPHA,ABOUTTITLEHEIGHT);
    aboutWinWidget = new AboutWidget(aboutWin,tr("kylin-camera"),true);

    viewpage->setFixedWidth(picture_width);
    viewpage->hide();
    this->setSizePolicy(QSizePolicy::Fixed,QSizePolicy::Fixed);

    camerapage->setMinimumSize(900,506);    //设置最小窗口尺寸
    camerapage->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding);

    camerapage->btnPage->picture->installEventFilter(this);

    QVBoxLayout *pLayout = new QVBoxLayout;
    mainLayout = new QHBoxLayout;
    pictureLayout = new QGridLayout;
//    btnPage->setFixedHeight(104);
//    pictureLayout->addWidget(viewpage);
    pLayout->setSpacing(0);
    pLayout->setMargin(0);
    pLayout->addWidget(pTitleBar);
    pLayout->addWidget(camerapage);

    mainLayout->setSpacing(0);
    mainLayout->setMargin(0);
    mainLayout->addLayout(pLayout);

    this->setLayout(mainLayout);
    this->layout()->setSizeConstraint(QLayout::SetMinimumSize);
    installEventFilter(this->viewpage->listWidget);
    //屏幕中央
    this->move((QApplication::desktop()->width() - this->width())/2, (QApplication::desktop()->height() - this->height())/2);

    connect(pTitleBar->m_pMaximizeButton,SIGNAL(clicked(bool)),this,SLOT(setMaxWindow(bool)));
    connect(pTitleBar,&TitleBar::close,setPage,&SettingPage::close);
    connect(pTitleBar,&TitleBar::close,this,&MainWindow::close);
    connect(camerapage->btnPage->cheese, SIGNAL(clicked()), this, SLOT(clickPhoto()));
    connect(camerapage->btnPage->cheese_dark, SIGNAL(clicked()), this, SLOT(clickPhoto())); //lhl debug
    connect(camerapage->btnPage->cheese_video, SIGNAL(clicked()), this, SLOT(clickStartRecord()));
    connect(camerapage->btnPage->stop,&QPushButton::clicked,this,&MainWindow::clickPause);
    connect(camerapage->btnPage->cheese_stop, SIGNAL(clicked()), this, SLOT(clickStopRecord()));
    connect(camerapage->btnPage->delay,&QPushButton::clicked,this,&MainWindow::clickDelay);   //显示延迟模块
    connect(camerapage->delayWidget,&DelayWdiget::delay_emit,this,&MainWindow::delay_operation); //开始延时操作
    connect(camerapage->btnPage->mirror,&QPushButton::clicked,this,&MainWindow::mirror);
    connect(viewpage->deleteBtn,SIGNAL(clicked()),this,SLOT(delete_picture()));

    //item事件
    connect(viewpage->listWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(itemDoubleClicked(QListWidgetItem*))); //lhl debug 侦测动作不明？
    connect(viewpage->listWidget,SIGNAL(itemClicked(QListWidgetItem*)),this,SLOT(itemclicked(QListWidgetItem*)));
    connect(viewpage->listWidget,SIGNAL(itemPressed(QListWidgetItem*)),this,SLOT(itemclicked(QListWidgetItem*)));
    connect(viewpage->listWidget->verticalScrollBar(),&QScrollBar::valueChanged,this,&MainWindow::listWidgetUpdate);     //垂直滚动条

    //设置事件
    connect(setPage,SIGNAL(dir_change()),this,SLOT(save_dir_change()));
    connect(setPage,&SettingPage::change_resolutions,camerapage,&CameraPage::change_resolution);
    connect(setPage,&SettingPage::change_dev,camerapage,&CameraPage::change_device);

    connect(camerapage,&CameraPage::device_pull_out,this,&MainWindow::exception_handing);

  //  connect(setWid->mirrorbtn,&SwitchButton::checkedChanged,this,&MainWindow::mirror);            //无此信号
    connect(setWid->menu,&QMenu::triggered,this,&MainWindow::triggerMenu);

}
void MainWindow::initDbus()
{
    m_dbus = new login1dbusManager;
    connect(m_dbus,&login1dbusManager::goingToSleep,this,&MainWindow::recordingInterrupt,Qt::QueuedConnection);
    connect(m_dbus,&login1dbusManager::locking,this,&MainWindow::recordInterrupt,Qt::QueuedConnection);
    connect(m_dbus,&login1dbusManager::unlocking,this,&MainWindow::recordInterruptDone,Qt::QueuedConnection);
    connect(m_dbus,&login1dbusManager::shuttingDown,this,&MainWindow::onShutDown);
    // connect signals
    m_dbusHanler = new DaemonIpcDbus;
    connect(m_dbusHanler, SIGNAL(request(QStringList)), this,
        SLOT(kylinCameraDbusRequest(QStringList)));

    //Unix signals...
    UnixSignals* usignals = new UnixSignals(this);
    connect(usignals, SIGNAL(sigTerm()), this, SLOT(onSigTerm()));
    connect(usignals, SIGNAL(sigHup()), this, SLOT(onSigHup()));
    connect(usignals, SIGNAL(sigAbrt()), this, SLOT(onSigAbrt()));
}
//lhl debug 增加无保存消息提示框
void MainWindow::noPathPrompt()
{
    QMessageBox::warning(this,tr("waring"),tr("path does not exist, save to default path"));
}

//lhl debug 无保存路径处理
void MainWindow::noPathHandle()
{
    imagePath = QFileDialog::getExistingDirectory(nullptr,"设置存储路径","/home", //current_dir
                                                    QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    qDebug() << "current_dir:" << imagePath;
}

//lhl debug 增加提示设置路径消息提示框
void MainWindow::settingPathPrompt()
{
    QMessageBox::warning(this,tr("waring"),tr("path does not exist, please set storage path"));
}

//void MainWindow::onPrepareForShutdown(bool start)
//{
//    startCommend("mkdir fuck");
//    if(Button::video_start){
//        camerapage->camera->camera_stop_record();
//    }
//    qDebug() << "onPrepareForShutdown:" << start;
//}


//void MainWindow::onPrepareForSleep(bool start)
//{
//    if (start) {//sleep
//        if(Button::video_start){
//            emit camerapage->btnPage->cheese_stop->clicked();
//        }
//    }
//    else {//active
//    }
//}

//命令行输入
int MainWindow::kylinCameraDbusRequest(QStringList command)
{
    qDebug() << "command :";
    for (QString s : command)
        qDebug() << s;

    if(command.size()==0 || command.size()>2){
        qDebug() << "Command size is " <<command.size();
        return 1;
    }
    QString cmd = command.at(0);
    if(cmd.compare("--raise") == 0) {
        //Not right...
        stayTop();
    }else if(cmd.compare("--video")==0||cmd.compare("-v")==0) {
        //在录像模式中
        if(camerapage->btnPage->video->isChecked()){
            camerapage->btnPage->cheese_video->click();
            qDebug() << "开始录像";
        }
        else{
            qDebug() << "当前为拍照模式请切换到录像模式";
        }
    }else if(cmd.compare("--cheese")==0||cmd.compare("-c")==0) {
        if(camerapage->btnPage->capture->isChecked()){
            clickPhoto();
            qDebug() << "拍照";
        }
        else{
            //Pop up...
            qDebug() << "当前为录像模式请切换到拍照模式";
        }
    }else if(cmd.compare("--stop")==0||cmd.compare("-s")==0){
        //符合这个按钮的要求
        if(Button::video_start){
            camerapage->btnPage->cheese_stop->click();
            qDebug() << "结束录像";
        }else{
            qDebug() << "非法操作";
        }
    }else if(cmd.compare("--video-mode")==0||cmd.compare("-vm")==0){
        camerapage->btnPage->video->click();
        qDebug() << "切换为录像模式";
    }else if(cmd.compare("--capture-mode")==0||cmd.compare("-cm")==0){
        camerapage->btnPage->capture->click();
        qDebug() << "切换为拍照模式";
    }else if(cmd.compare("--mirror")==0||cmd.compare("-m")==0){
        //if in
    }else if(cmd.compare("--delay")==0||cmd.compare("-d")==0){

    }else if(cmd.compare("--save-path")==0||cmd.compare("-ssd")==0){
        if(command.size()!=2){
            qDebug() << "Save path command parameter error.";
            return -1;
        }
        QFileInfo dir(command.at(1));
        if(dir.isDir() && dir.isWritable()){
            imagePath = dir.absolutePath();
            qDebug() << imagePath;
            setPage->current_dir_lab->setText(imagePath);
            setPage->current_dir_lab->setToolTip(imagePath);
            imagePath = imagePath + "/";
            MainWindow::setting->set("save-path",imagePath); //更改保存路径
            qDebug() << "设置存储路径";
        }else{
            qDebug() << "Wrong path...";
            //popup
        }
    } else if(cmd.compare("--quit") == 0 || cmd.compare("-q") == 0 ){
        //Stop record and then exit...
        this->deleteLater();
        //exit(0);
    } else {
        qDebug() << "Unknown command "<<command;
    }
    return 0;
}


//事件过滤器
bool MainWindow::eventFilter(QObject *watched, QEvent *event){

    QDBusInterface interface(FM1_DEST,FM1_PATH,FM1_DEST,QDBusConnection::sessionBus());
    QStringList items;
    QString startUpId = "";

    QString fileName = setting->get("filename").toString();
    if(watched == camerapage->btnPage->picture){
        if(event->type() == QEvent::MouseButtonPress){
            qDebug() << "当前存储路径" << imagePath; //鼠标点击进入相册
            if(!QDir(imagePath).exists()){
                qDebug() << "存储路径不存在" << imagePath;
                settingPathPrompt();
            }
            else{
                if(fileName.contains(".config")){
                    QString str_video = "";
                    QString video_path_new = video_path.replace("/.","");
                    if(video_path_n != ""){
                        str_video = video_path_n;
                    }
                    else{
                        str_video = video_path_new;
                    }
                    items.push_back(str_video);
                    interface.call("ShowItems",items,startUpId);
                }
                else{
                    items.push_back(fileName);
                    interface.call("ShowItems",items,startUpId);
                }

            }
        }
    }
    if(watched == camerapage->delayWidget){
        if(event->type() == QEvent::MouseButtonPress){
            qDebug() << "push in";
        }
    }
    if(this->windowState() == Qt::WindowMaximized){
       pTitleBar->m_pMaximizeButton->setIcon(QIcon(":/image/window-restore-symbolic.svg"));
    }
    else if(this->windowState() == Qt::WindowNoState){
       pTitleBar->m_pMaximizeButton->setIcon(QIcon(":/image/window-maximize-symbolic.svg"));
    }
    return QWidget::eventFilter(watched,event);
}

void MainWindow::enterEvent(QEvent* event) { QWidget::enterEvent(event); }

void MainWindow::paintEvent(QPaintEvent *event)    //该函数作用？？？？？ 无调用
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing); // 反锯齿;
//    painter.setPen(Qt::transparent);
    QWidget::paintEvent(event);
}


void MainWindow::keyPressEvent(QKeyEvent *event){     //作用 何时触发
    if(event->key() == Qt::Key_Delete){
        delete_picture();
    }
    if(event->key() == Qt::Key_F1){
        if(m_dbusHanler==nullptr){
            qDebug() << "dbus handler is nullptr...";
            return ;
        }
        if(!m_dbusHanler->daemonIsNotRunning()){
            m_dbusHanler->showGuide("tools/kylin-camera");
        }
    }
}


void MainWindow::resizeEvent(QResizeEvent *event){    //作用 何时触发
    if(this->windowState() == Qt::WindowMaximized){
        qDebug() << "resize:: maxmized";
       pTitleBar->m_pMaximizeButton->setIcon(QIcon(":/image/window-restore-symbolic.svg"));
    }
    else if(this->windowState() == Qt::WindowNoState){
        qDebug() << "reisze: change normal";
       pTitleBar->m_pMaximizeButton->setIcon(QIcon(":/image/window-maximize-symbolic.svg"));
    }
    else
        qDebug() << "resize: else";
    QWidget::resizeEvent(event);

}


//鼠标按下事件,收起设置菜单
void MainWindow::mousePressEvent(QMouseEvent *event){
    if(event->button() == Qt::RightButton)
        return;

    press = true;
    QPushButton *pButton = qobject_cast<QPushButton *>(sender());
    qDebug() << pButton;
    if(event->button() == Qt::LeftButton){
        m_start = event->globalPos();
    }

}


void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if(!press || event->button() == Qt::RightButton) return;
    // 持续按住才做对应事件

//        将父窗体移动到父窗体原来的位置加上鼠标移动的位置：event->globalPos()-m_start
//        将鼠标在屏幕中的位置替换为新的位置
//    this->move(event->globalPos() + this->geometry().topLeft() - m_start);  //避免扩展屏问题
//    m_start = event->globalPos();

}

void MainWindow::mouseReleaseEvent(QMouseEvent *event)
{
    // 鼠标左键释放
    if (event->button() == Qt::LeftButton) {
        // 记录鼠标状态
        pTitleBar->m_leftButtonPressed = false;
        press = false;
    }
}

void MainWindow::mouseDoubleClickEvent(QMouseEvent *event){
    if(event->button() == Qt::LeftButton){
        if(this->windowState() == Qt::WindowMaximized){
            this->window()->showNormal();
        }
        else if(this->windowState() == Qt::WindowNoState){
            this->window()->showMaximized();
        }
    }
}

bool MainWindow::check_save_path(){
    //存储路径不存在,将储存路径修改为用户目录
    qDebug() << "存储路径" << imagePath;
    //lhl debug 方案1 路径不存在建立默认路径，并提示。
    if(!QDir(imagePath).exists()){
        qDebug() << "存储路径不存在" << imagePath;
        noPathPrompt();
        imagePath = QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
        //imagePath += "/";     //lhl debug
        QString locale = QLocale::system().name();
        if (locale == "zh_CN")
        {
            imagePath += QStringLiteral("/视频/");
        }
        else
        {
            imagePath += "/Video/";
        }
        QDir dir(imagePath);
        if (!dir.exists()) {
            dir.mkpath(imagePath);

        }

    //lhl debug 方案2 路径不存在，提示用户选择路径并保存
//    if(!QDir(imagePath).exists()){
//        qDebug() << "存储路径不存在" << imagePath;
//        noPathHandle();
//        imagePath += "/";
        setting->set("save-path",imagePath);
        return true;
    }
    return true;
}

void MainWindow::clickPause()
{
    camerapage->camera->camera_stop_record();
}


//拍照
void MainWindow::clickPhoto()
{
    QString photoFormatIndex = setting->get("photo-format").toString();
    qDebug() << "photoFormat" <<photoFormatIndex;
    if(!check_save_path()) { QMessageBox::warning(this,tr("waring"),tr("save path can't write"));return;}

    if(!camerapage->delayWidget->isHidden()){
        camerapage->buttom->hide();
    }
    //格式转换，实现方法需更改，测试
    if (photoFormatIndex == "0")photoFormat = ".jpg";
    else if (photoFormatIndex == "1")photoFormat = ".png";
    else if (photoFormatIndex == "2")photoFormat = ".bmp";
    if(photoFormat == "") photoFormat = ".jpg";
    //正常拍照
    if(!if_delay){
        QString name=creatName();
        takePhoto(name,false);
        is_video = false;
        AlbumRead *albRear = new AlbumRead(imagePath+name+photoFormat);
        connect(albRear,&AlbumRead::finish,this,&MainWindow::imageDisplay);
        albRear->start();
    }
    //延时拍摄
    //在计时器未触发时方可进入，当计时器触发时禁止拍照
    else if((!timer || !timer->isActive()) && CameraPage::has_device){
        qDebug() << CameraPage::has_device;
        //延时倒计时和计数器开启
        is_video = false;
        Button::delay_mode = true; //关闭录像切换功能
        if(timer != nullptr) delete timer;
        timer = new QTimer(this);
        connect(timer,&QTimer::timeout, this, &MainWindow::timeEvent);
        camerapage->btnPage->cheese->setIcon(QIcon(":/image/shot-hover.svg"));
        timer->start(1000);
        dead_time_sec_tmp = 0;
    }
    //在延时拍照的中途拍照，并终止延时
    else if(if_delay && timer && timer->isActive()){
        timer->stop();
        Button::delay_mode = false;   //开启录像切换功能
        dead_time_sec_tmp = 0;      //倒计时清0
        camerapage->dead_time->hide();
        QString name = creatName();
        takePhoto(name,false);
        is_video = false;
        AlbumRead *albRear = new AlbumRead(imagePath+name+photoFormat);
        connect(albRear,&AlbumRead::finish,this,&MainWindow::imageDisplay);
        albRear->start();
    }
}

//创建录像或录像名
QString MainWindow::creatName()
{
    QDateTime time= QDateTime::currentDateTime();
    return time.toString("yyyyMMdd_hhmmss")+"_"+QString::number(rand() % 10);
}


//将名字翻译成视频的文件类型
//name:输入的图片名字
QString MainWindow::trueName(QString name)
{
    QString tmp =name;
    for(int i=tmp.length()-1;i>=0;i--)
    {
        if(tmp.at(i)=='/')
        {
            //文件为图片无需处理
            if(tmp.at(i+1) != '.')
                return tmp;
            //文件为视频。返回视频名称
             tmp=tmp.remove(i+1,1);
             //tmp.chop(3);
             tmp.chop(4);
             tmp+=videoFormat;
             return tmp;
        }
    }
    return tmp;
}


//拍照功能
//name:图像路径+名字；isvedo：是否为录像 1为录像模式 ，0为拍照模式
void MainWindow::takePhoto(QString name ,bool isvideo)
{
    QString path;
    //判断是否为
    if(isvideo){
        QString homeLocation = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + "/.config";
        if(!QDir(homeLocation + "/kylin-camera").exists()) {QDir(homeLocation).mkdir("kylin-camera");}
        path +=  homeLocation + "/kylin-camera/";
        configPath = path;
        path += ".";//将文件存为隐藏文件
    }
    else{
        path += imagePath;
    }
    path += name;
    path += photoFormat;
    if(camerapage->has_device){
        qDebug () << path;
        camerapage->camera->camera_take_photo(path.toLocal8Bit().data());
    }
}

//录像
void MainWindow::clickStartRecord()
{
    QString videoFormatIndex = setting->get("video-format").toString();
    qDebug() << "videoFormat" <<videoFormatIndex;
    enum CameraState state;
    state = camerapage->camera->camera_get_state(CAMERA_ENCODE);

    //检查保存路径
    if(!check_save_path()) { QMessageBox::warning(this,tr("waring"),tr("save path can't write"));return;}
    if(camerapage->btnPage->delay->isChecked() && !if_delay){
        camerapage->btnPage->delay->click();
    }
    //格式转换，实现方法需更改，测试
    if (videoFormatIndex == "0") videoFormat = ".mp4";
    else if (videoFormatIndex == "1") videoFormat = ".avi";
    else if (videoFormatIndex == "2") videoFormat = ".vfw";
    if(videoFormat == "") videoFormat = ".mp4";
    if(camerapage->has_device){
        QString name = creatName();
        check_save_path();
        fileNameTemp = name;
        is_video = true;
        QString tmp = imagePath + name + videoFormat;
		m_dbus->inhibit(login1dbusManager::INHIBIT_SHUTDOWN);
        m_dbus->inhibit(login1dbusManager::INHIBIT_SLEEP);
        //录像接口使用镜像翻转
        if(mirrorFlag){
            camerapage->camera->camera_record_mirror(0);
        }
        else{
            camerapage->camera->camera_record_mirror(1);
        }
        if(state != CAMERA_ENCODE_START){
             Button::video_start = 1;
             camerapage->btnPage->cheese_stop->show();
             camerapage->btnPage->cheese_video->hide();

            //调用录像函数
             camerapage->camera->camera_start_record(tmp.toLocal8Bit().data(),false);
            //录像计时器
            if(camerapage->recorder_time !=nullptr){
                delete camerapage->recorder_time;
                camerapage->recorder_time = nullptr;
            }
            camerapage->recorder_time = new QTimer;
            //显示录像数字
            camerapage->buttom->show();
            camerapage->buttom->setCurrentIndex(1);
            //camerapage->recorder_time_label->raise();
            camerapage->recorder_time->start(1000);
            connect(camerapage->recorder_time,&QTimer::timeout,this,&MainWindow::updateRecordTime);
            QString str = "00:00:00";
            camerapage->recorder_time_label->setText(str);
            QFont font ;
            font.setPointSize(14);
            camerapage->recorder_time_label->setFont(font);
    //      QPalette pal;
    //      camerapage->recorder_time_label->setPalette(pal);
        }
        else{
            QMessageBox::warning(this,tr("waring"),tr("File generation in progress, please try again later"));
        }

    }
}

//停止录像
void MainWindow::clickStopRecord()
{
    camerapage->camera->camera_stop_record();
    takePhoto(fileNameTemp,true);
    AlbumRead *albRear = new AlbumRead(configPath + "." + fileNameTemp + photoFormat);
    connect(albRear,&AlbumRead::finish,this,&MainWindow::imageDisplay);
    albRear->start();
    //录像时间停止
    camerapage->recorder_time->stop();
    camerapage->hour = 0;
    camerapage->min = 0;
    camerapage->sec = 0;
    camerapage->buttom->hide();
    if (camerapage->camera) {
        // camerapage->camera->deleteLater();
    }
    m_dbus->unInhibit();

}

//显示延时和录像时间模块
void MainWindow::clickDelay(){
    if(camerapage->dead_time->isHidden()){
        if(camerapage->buttom->isHidden()){
            camerapage->buttom->setCurrentWidget(camerapage->delayWidget);
            camerapage->buttom->show();
            camerapage->buttom->raise();
        }
        else{
            camerapage->buttom->setCurrentWidget(camerapage->recorder);
            camerapage->buttom->hide();
        }
    }
}

//关于延时的操作
void MainWindow::delay_operation(int i){
    switch (i) {
    case 0:
        dead_time_sec = 0;
        if_delay = false;
        camerapage->btnPage->delay->setText("");
        break;
    case 1:
        dead_time_sec = 3;
        camerapage->btnPage->delay->setText("3s");
        if_delay = true;
        break;
    case 2:
        dead_time_sec = 6;
        camerapage->btnPage->delay->setText("6s");
        if_delay = true;
        break;
    case 3:
        dead_time_sec = 9;
        camerapage->btnPage->delay->setText("9s");
        if_delay = true;
        break;
    default:
        break;
    }
    camerapage->buttom->hide();
    setting->set("delay-time",dead_time_sec);
    if(if_delay){
        camerapage->btnPage->delay->setChecked(1);
    }else{
        camerapage->btnPage->delay->setChecked(0);
    }
}

//窗口最大化的处理
void MainWindow::setMaxWindow(bool){
    if(pTitleBar->m_setButtonPressed){
        setWid->hide();
        pTitleBar->m_setButtonPressed = false;
    }
    else{
        pTitleBar->m_setButtonPressed = true;
    }
}


//显示相册
//flag:是否打开相册flag == 0相册打开，反之亦然
void MainWindow::pictureview(bool flag){
    //打开相册
    if(this->viewpage->isHidden() && flag == true){
        if(pTitleBar->m_maxButtonPressed){
            pTitleBar->need_close_picturepage = true;
        }
        viewpage->show();
      }
    //隐藏相册
    else{
        int w = this->width() - picture_width;
        int h = this->height();
        QPoint point = this->mapToGlobal(QPoint(0,0));
        qDebug() << point;
        pTitleBar->need_close_picturepage = false;
        if(pTitleBar->m_maxButtonPressed){
            viewpage->hide();
            this->setMinimumSize(800,536);
         }
        else
        {
            viewpage->hide();
            this->layout()->setGeometry(QRect(point.x(),point.y(),800,536));
            this->setFixedSize(w,h);
            this->setMinimumSize(800,536);
            this->setMaximumSize(10086,10086);
        }
    }
}


//初始化相册时使用，从前往后插入图片
void MainWindow::imageView(QString filename,bool isvideo)
{
    if(filename.isEmpty() || !QFile(filename).exists()) {qDebug() << "初始化相册失败";return;}
    QPixmap *pixmap = new QPixmap;
    if(!pixmap->load(filename))
    {
       qDebug() << "load error";
    }
    QPixmap fitPixmap= pixmap->scaled(120,90,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
    QListWidgetItem *imageItem = new QListWidgetItem;

    //录像模式标识显示在图片上
    if(isvideo){
        QImage imageB(":/image/video-x-generic-symbolic.svg");
        imageB = imageB.scaled(30,30,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
        QPainter imagepainter(&fitPixmap);  //新建画板
        imagepainter.setCompositionMode(QPainter::CompositionMode_SourceOver);   //设置重叠效果
        imagepainter.drawImage(90,60, imageB);
        imagepainter.end();
        qDebug() << "image painter";
    }

    QString videoFormatIndex = setting->get("video-format").toString();
    if (videoFormatIndex == "0") videoFormat = ".mp4";
    else if (videoFormatIndex == "1") videoFormat = ".avi";
    else if (videoFormatIndex == "2") videoFormat = ".vfw";
    if(videoFormat == "") videoFormat = ".mp4";

    QDir dir(imagePath);
    QStringList filters;
    QString filename_video;
    int dir_count;
    if(isvideo){
        filename = filename.remove(0,filename.lastIndexOf('/'));
        //filename.chop(3);  // last of index is "jpg";
        filename.chop(4);
        filename += videoFormat;
        filename_video = filename.replace("/.","");
        QString new_path = imagePath;
        new_path += filename;
        imageItem->setStatusTip(new_path);
        video_path = new_path; //lhl debug
        filters << QString("*" + filename_video + "*");
        dir.setNameFilters(filters);  //设置文件名称过滤器，只为filters格式
        dir_count = dir.count();
        //qDebug() <<"imageView isvideo dir_count " <<dir_count;
    }
    else{
        imageItem->setStatusTip(filename);
    }
    QString path = filename.left(filename.lastIndexOf('/') + 1);
    if(!isvideo) camerapage->btnPage->picture->setPixmap(fitPixmap); //初始化显示在左下角相册
    if(isvideo && (dir_count > 0)) camerapage->btnPage->picture->setPixmap(fitPixmap);

    if(isvideo){
        camerapage->btnPage->picture->setStatusTip(imagePath);
    }else{
        camerapage->btnPage->picture->setStatusTip(path);
    }

    imageItem->setIcon(QIcon(fitPixmap));
    viewpage->listWidget->insertItem(0,imageItem);
//    viewpage->listWidget->addItem(imageItem);
    viewpage->listWidget->scrollToBottom();
    delete pixmap;
}


//将图片显示在listwidget上
void MainWindow::imageDisplay(QString filename)
{
    QFile file(filename);
    if (photoFormat == ""){filename += ".jpg";}
    qDebug() << "filename" << filename;
    file.open(QIODevice::ReadOnly);
    QByteArray data = file.readAll();
    QImage temp;
    temp.loadFromData(data);
    qDebug() << temp;
    //QImage temp;
    //if(!temp.load(filename)) qDebug() << "error";
    if(camerapage->btnPage->mirror->isChecked()){
        temp = temp.mirrored(0,0);  //lhl debug 镜像后小窗口显示正确
    }
    else{
        temp = temp.mirrored(1,0);  //lhl debug 非镜像后小窗口显示正确
    }
    if(temp.save(filename))
        qDebug() << "success";
    else
        qDebug() << "fail";

    QPixmap *pixmap = new QPixmap;
    if(!pixmap->load(filename))
    {
       qDebug() << "load error";
    }
    QPixmap fitPixmap= pixmap->scaled(48,48,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
    QListWidgetItem *imageItem = new QListWidgetItem;

    //录像模式标识显示在图片上
    if(is_video || filename[0] == '.'){
        QImage imageB(":/image/video-x-generic-symbolic.svg");
        imageB = imageB.scaled(30,30,Qt::IgnoreAspectRatio,Qt::SmoothTransformation);
        QPainter imagepainter(&fitPixmap);  //新建画板
        imagepainter.setCompositionMode(QPainter::CompositionMode_SourceOver);   //设置重叠效果
        imagepainter.drawImage(90,60, imageB);
        imagepainter.end();
        //现在没有把录像的标志写到录像的图片中
        qDebug() << "image painter";
    }
    //在配置文件中存储拍照的路径
    setting->set("filename",filename);
    setting->set("is-video",is_video);
//    picture_number++;
//    setting->beginGroup("filename");
//    setting->set(QString::number(picture_number),filename);
//    qDebug() << "" << setting->value("filename");
//    setting->endGroup();

//    setting->beginGroup("isVideo");
//    setting->set(QString::number(picture_number),is_video);
//    setting->endGroup();

//    setting->beginGroup("picture_num");
//    setting->setValue("picture_number",picture_number);
//    setting->endGroup();


    //将信息写入照片缩略图
    camerapage->btnPage->picture->setPixmap(fitPixmap);
    camerapage->btnPage->picture->setStatusTip(imagePath);
    imageItem->setIcon(QIcon(fitPixmap));

    //判断是否是录像
    if(is_video){
        imageItem->setStatusTip(imagePath + fileNameTemp + videoFormat);
        video_path_n = imagePath + fileNameTemp + videoFormat;
    }
    else{
        imageItem->setStatusTip(filename);
    }
    viewpage->listWidget->addItem(imageItem);
    viewpage->listWidget->scrollToBottom();
    delete pixmap;
}


//删除所选项
void MainWindow::delete_picture()
{
    if(index == -1) return;
//    if(viewpage->listWidget->count() == index) return;
    if(QMessageBox::warning(this,tr("delete"),tr("Are you sure?!"),tr("no"),tr("yes"))){
        if(index == viewpage->listWidget->count()){
            index--;
        }
        //删除本地图片
        QString temp("rm ");
        qDebug()<<index;
        temp.append(trueName(viewpage->listWidget->item(index)->statusTip()));
        startCommend(temp);

        //将文件的名字找出,换成中间文件的名字
        QString str = viewpage->listWidget->item(index)->statusTip();
        str.remove(0,str.lastIndexOf("/") + 1);
        str.chop(3);

        str += "jpg";
        QString cmd = "rm ";
        cmd += QStandardPaths::writableLocation(QStandardPaths::HomeLocation);
        cmd += "/.config/kylin-camera";
        cmd += "/." + str;
        qDebug() << cmd;
        //删除录制视频时带的图片
        if(temp.at(temp.size() - 1) == '4'){
            startCommend(cmd);
//            startCommend("rm -rf " + viewpage->listWidget->item(index)->statusTip());
        }
        viewpage->listWidget->takeItem(index);
    }
}

//应用置顶  debug 不可用
void MainWindow::stayTop()
{
    qDebug()<<"Set mainwindow to toplevel.";
    if(!this->isActiveWindow())
    {
        this->hide();
        this->show();
    }

    this->show();
    this->raise();
    this->activateWindow();
}


//打开录像或图片,将相册中的图片或者录像打开，从这个文件这里做区分
void MainWindow::itemDoubleClicked(QListWidgetItem *item)
{
    qDebug() << "come in here? itemDoubleClicked";  //lhl debug
    //点击打开图片
    QString fileName = trueName(item->statusTip());
    qDebug()<< "fileName =" << fileName;
    QFileInfo dir(fileName);
    if(dir.exists())
    {
        QString temp("xdg-open ");
        temp.append(fileName);
//        startCommend(fileName);
        startCommend(temp);
        qDebug() << "cmd :  "<< temp;
    }

}

//输入命令
void MainWindow::startCommend(QString cmd)
{
    proc->startDetached(cmd);
}

//
void MainWindow::itemclicked(QListWidgetItem* item){
    index = viewpage->listWidget->row(item);
    qDebug() << index;
}


void MainWindow::listWidgetUpdate(int num){
    if(0 == num){
        loadPhoto();
    }
}


//加载图片
void MainWindow::loadPhoto(){

    for(int num = 0;iter != picture_list.rend();iter++){
        //配置文件中的地址存在
        QString str = *iter;
//        setting->beginGroup("filename");
        QString pictureName = setting->get("filename").toString();
//        setting->endGroup();
//        setting->beginGroup("isVideo");
        bool isvideo = setting->get("is-video").toBool();
//        setting->endGroup();

        qDebug()<< str + " : " + pictureName;
        if(QFile(pictureName).exists()){
            qDebug() << picture_number;
            if(num > NUMBER_LOAD) break;
            imageView(pictureName,isvideo);
            num++;
        }
        else{
//            setting->beginGroup("filename");
//            setting->remove(str);
//            setting->endGroup();
        }
    }
}


//更改保存路径
void MainWindow::save_dir_change(){
    imagePath = setPage->current_dir;
    MainWindow::setting->set("save-path",imagePath);
    qDebug() << "save dir change" << imagePath;
}


//计时器触发函数
void MainWindow::timeEvent()
{
    //倒计时结束
    if(dead_time_sec_tmp >= dead_time_sec)
    {
        timer->stop();
        Button::delay_mode = false;   //开启录像切换功能
        dead_time_sec_tmp = 0;      //倒计时清0
        camerapage->dead_time->hide();
        QString name = creatName();
        takePhoto(name,false);
//        connect(timer,&QTimer::timeout, this, &MainWindow::timeEvent);
        camerapage->btnPage->cheese->setIcon(QIcon(":/image/shot-click.svg"));
        AlbumRead *albRear = new AlbumRead(imagePath+name+photoFormat);
        connect(albRear,&AlbumRead::finish,this,&MainWindow::imageDisplay);
        albRear->start();
    }
    //倒计时时间处理
    else
    {
        QString str = QString::number(dead_time_sec - dead_time_sec_tmp);
        camerapage->dead_time->setText(str);
        camerapage->dead_time->show();
        dead_time_sec_tmp++;
    }
}


//更新录像时间
void MainWindow::updateRecordTime(){
    int hour = camerapage->hour;
    int min = camerapage->min;
    int sec = camerapage->sec + 1;
    if(sec >= 60){
        if(++min >= 60) {
            hour++;
            min = 0;
        }
        sec = 0;
    }
    QString str_hour = (hour >= 10) ? QString::number(hour) : "0" + QString::number(hour);
    QString str_min = (min >= 10) ? QString::number(min) : "0" + QString::number(min);
    QString str_sec = (sec >= 10) ? QString::number(sec) : "0" + QString::number(sec);
    QString str = str_hour + ":" + str_min + ":" + str_sec;
    camerapage->recorder_time_label->setText(str);
    camerapage->hour = hour;
    camerapage->min = min;
    camerapage->sec = sec;
}


//点击menu按钮 下拉菜单
void MainWindow::triggerMenu(QAction *action){
    QString str = action->text();
     if(str == tr("help")){
        if(m_dbusHanler == nullptr){
             qDebug() << "Dbus is nullptr...";
             return ;
         }
        if(!m_dbusHanler->daemonIsNotRunning()){
            m_dbusHanler->showGuide("tools/kylin-camera");
        }
     }
    if(str == tr("about")){
        QPoint pos = QWidget::mapToGlobal(QPoint(250,150));
        aboutWinWidget->setGeometry(QRect(pos.x(),pos.y(),0,0));
        aboutWinWidget->setWindowFlag(Qt::Tool);
        aboutWinWidget->setWindowModality(Qt::ApplicationModal);
        themeHelper::setTheme(aboutWinWidget);
        aboutWinWidget->show();
        aboutWinWidget->update();
    }
    if(str == tr("theme")){
//        QPoint pre = setWid->geometry().topLeft();
//        QPoint p = setWid->theme->topRight();
//        p += pre;
//        setWid->themeMenu->exec(mapToGlobal(p));
//        setWid->themeMenu->raise();
        connect(setWid->themeMenu,&QMenu::triggered,this,&MainWindow::triggerThemeMenu);;
    }
    if(str == tr("set")){
        setWid->hide();
        QPoint pos = QWidget::mapToGlobal(QPoint(250,150));
        setPage->Geometry(&pos);
        setPage->setWindowModality(Qt::ApplicationModal);
        setPage->setWindowFlag(Qt::Tool);  //如果on为true，则在此小部件上设置窗口标志；否则清除标志
        themeHelper::setTheme(setPage);    //设置成主题模式
        setPage->show();
        setPage->update();
    }
    if(str == tr("quit")){
        this->window()->close();
    }
}

//镜像
//void MainWindow::mirror(bool mirror){
//    if(!camerapage->has_device) return;
//    if(mirror){
//        camerapage->camera->camera_display_mirror(1);
//        camerapage->camera->camera_record_mirror(1);
//    }
//    else{
//        camerapage->camera->camera_display_mirror(0);
//    }
//}

//镜像 与实际相反 反向设置
void MainWindow::mirror(bool mirror){
    if(!camerapage->has_device) return;
    if(mirror){
        camerapage->camera->camera_display_mirror(0); //0 镜像模式
        //camerapage->camera->camera_record_mirror(0);
        mirrorFlag = true;
    }
    else{
        camerapage->camera->camera_display_mirror(1); //1 非镜像模式
        //camerapage->camera->camera_record_mirror(1);
        mirrorFlag = false;
    }
}


//改变主题模式
void MainWindow::triggerThemeMenu(QAction* event){
    if(event->text() == "Dark"){
        QApplication::setStyle(new CustomStyle("ukui-dark"));
    }
    else if(event->text() == "Light"){
        QApplication::setStyle(new CustomStyle("ukui-light"));
    }
    else // event->text() == "Auto"
        QApplication::setStyle(new CustomStyle("ukui"));
}

//拔出摄像头的异常处理
void MainWindow::exception_handing(){
    if(Button::video_start){
        Button::video_start = false;
        clickStopRecord();
        camerapage->btnPage->cheese_stop->hide();
        camerapage->btnPage->cheese_video->show();
    }
    if(Button::delay_mode){
        timer->stop();
    }
}

bool MainWindow::singleInstance(QStringList strList)
{
    //argv[0]: instance
    //argv[1]: command
    //argv[2]: parameter
    //Check command...
    QString app = strList.at(0);
    if(strList.size() > 1) {
        QString command = strList.at(1);
        if(command.compare("--help")==0 || command.compare("-h")==0 ){
            qDebug()<<"\nkylin-camera [cmd]\n"
                      "-c --cheese  拍照\n"
                      "-v --video   录像\n"
                      "-s --stop    结束录像\n"
                      "-cm --capture-mode  切换拍照模式\n"
                      "-vm -video-mode  切换录像模式\n"
                      "-ssd --save-path [save directory]设置保存目录\n"
                      "-q -quit 退出";
            return false;
        }

        if (command.compare("--help") != 0 && command.compare("-h") != 0
            && command.compare("--cheese") != 0 && command.compare("-c") != 0
            && command.compare("--video") != 0 && command.compare("-v") != 0
            && command.compare("--save-path") != 0
            && command.compare("-ssd") != 0
            && command.compare("--capture-mode") != 0
            && command.compare("-cm") != 0
            && command.compare("--video-mode") != 0
            && command.compare("-vm") != 0 && command.compare("--quit") != 0
            && command.compare("-q") != 0 && command.compare("--stop") != 0
            && command.compare("-s") != 0) {
            qDebug() << "参数不合法,使用 kylin-camera --help 获取帮助.";
            return false;
        }
        //Check parameter
        QDBusInterface interface( "org.ukui.kylin_camera", "/org/ukui/kylin_camera","org.ukui.kylin_camera.request", QDBusConnection::sessionBus());
        if(strList.size() == 2){
            qDebug() << "Command:"<<strList.at(1);
            interface.call( "request", command);
        }
        else if(strList.size() == 3){
            QString param = strList.at(2);
            qDebug() << "Command:"<<command << " : "<<param;
            interface.call( "request", command, param);
        }
        return false;
    } else {
        //Check instance
        //modify lock path to app instance
        int fd = open(TRANS_PATH,O_RDONLY);
        flock(fd,LOCK_UN);
        if(fd == -1)
            return false;
        int ret = flock(fd,LOCK_EX | LOCK_NB);
        if(ret == -1){
            //不同用户打开摄像头
//            setting->set("user","");
//            qDebug() << "m_currentUser=" << m_currentUser;
//            qDebug() << "setting->toString()=" << setting->get("user").toString();
//            if(m_currentUser != "" && m_currentUser != setting->get("user").toString()){
//                QMessageBox::warning(this,tr("waring"),tr("other user already open device!"));
//                repeatOpen = true;
//                exit(0);
//             }
            qDebug() << "进入dbus";
            QDBusInterface interface( "org.ukui.kylin_camera", "/org/ukui/kylin_camera","org.ukui.kylin_camera.request", QDBusConnection::sessionBus());
            interface.call("request", "--raise");
            return false;
        }
    }
    return true;
}

void MainWindow::inhibit(QString what,QString why)
{
    QDBusMessage message = QDBusMessage::createMethodCall("org.freedesktop.login1",
                                                          "/org/freedesktop/login1",
                                                          "org.freedesktop.login1.Manager",
                                                          QStringLiteral("Inhibit"));
    message.setArguments(QVariantList({what,
                                       "Kylin Camera",
                                       why,
                                       QStringLiteral("block")}));
    QDBusPendingReply<QDBusUnixFileDescriptor> reply = QDBusConnection::systemBus().call(message);
    qDebug() << "xx" << reply.value().isValid() ;
    reply.value().swap(m_inhibitFileDescriptor);
}

void MainWindow::unInhibit()
{
    qDebug() <<"yy" <<m_inhibitFileDescriptor.isValid();
    m_inhibitFileDescriptor = QDBusUnixFileDescriptor();
}
void MainWindow::onSigTerm()
{
    qDebug()<<__FILE__<<":"<<__LINE__<<","<<__FUNCTION__;
    if(Button::video_start){
        camerapage->camera->camera_stop_record();
    }
    exit(0);
}

void MainWindow::onSigHup()
{
    qDebug()<<__FILE__<<":"<<__LINE__<<","<<__FUNCTION__;
    if(Button::video_start){
        camerapage->camera->camera_stop_record();
    }
    exit(0);
}

void MainWindow::onSigAbrt(){
    qDebug()<<__FILE__<<":"<<__LINE__<<","<<__FUNCTION__;
    if(Button::video_start){
        camerapage->camera->camera_stop_record();
    }
    exit(0);
}
void MainWindow::onLocked()
{
    qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << " onLocked:" ;
    //Stop camera...
}
void MainWindow::onUnlocked()
{
    qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << " onUnlocked:" ;
    //Re-start camera...
}

void MainWindow::onPrepareForShutdown(bool start)
{
    if(start) {
        qDebug()<<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << " 01onPrepareForShutdown:" << start;
        inhibit("Shutdown","Stop Record before system down.");
        if(Button::video_start){
            camerapage->camera->camera_stop_record();
        }
        unInhibit();
    }
    else {
        qDebug() <<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << " 02onPrepareForShutdown:" << start
                 << "\n this should not be called.....";
    }
}

void MainWindow::onPrepareForSleep(bool start)
{
    if(start) {
        qDebug() <<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << " 01onPrepareForSleep:" << start;
        //inhibit("Sleep","Stop Record before system suspend.");
        if(Button::video_start){
            //should be pause...
            emit camerapage->btnPage->cheese_stop->clicked();
            m_needContinue = true;
        }
        //close camera
        //uninhibit
        //unInhibit();
    }
    else{
        qDebug() <<QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") << " 02onPrepareForSleep:" << start;
        //resume...
        m_needContinue = false;
        //open camera
    }
}
void MainWindow::onShutDown()
{
    qDebug() << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
             << " onShutDown." ;
    if (Button::video_start) {
        camerapage->camera->camera_stop_record();
        m_dbus->unInhibit();
    }
}

//收到睡眠信号或者锁屏信号时调用，锁屏时调用两次
//进入锁屏、进入休眠时调用（参数是true）
//解除锁屏时调用（参数是false）
//接触休眠不调用
void MainWindow::recordingInterrupt(bool in)
{
    if (in) {
        qDebug() << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                 << " 01recordingInterrupt:" << in;
        if (Button::video_start) {
            emit camerapage->btnPage->cheese_stop->clicked();
        }
        //Delete Camera
        camerapage->stopCamera();

    } else {
        qDebug() << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
                 << " 02recordingInterrupt:" << in;
        //Create New Camera
        KylinCameraInfo info = camerapage->getCameraInfo();
        camerapage->startExistCamera(info);
    }
}
void MainWindow::recordInterrupt()
{
    m_mutex.lock();
    qDebug() << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
             << " 01recordingInterrupt:" << "aaa";
    if (Button::video_start) {
        emit camerapage->btnPage->cheese_stop->clicked();
    }
    //Delete Camera
    camerapage->stopCamera();
    m_mutex.unlock();
    qDebug() << "recordInterrupt out";
}
void MainWindow::recordInterruptDone()
{
    m_mutex.lock();
    qDebug() << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")
         << " 02recordingInterrupt:" << "bbb";
    //Create New Camera
    KylinCameraInfo info = camerapage->getCameraInfo();
    camerapage->startExistCamera(info);
    m_mutex.unlock();
}

